package com.hutra.utils {
	import flash.events.*;
	import flash.net.*;
	
	/**
	 * @author hungconcon
	 */
	public class SharedSoundData extends Object {
		private var isMute:Boolean;
		private var cachedNonNormalizedVolume:Number = 100;
		private var soundSharedObject:SharedObject;
		private var soundData:Object;
		private static var SOUND_DATA_KEY:String = "soundData";
		
		public function SharedSoundData(value:Boolean) {
			var useSharedObject:Boolean;
			useSharedObject = value;
			if (useSharedObject) {
				try {
					SharedObject.defaultObjectEncoding = ObjectEncoding.AMF0;
					soundSharedObject = SharedObject.getLocal(SOUND_DATA_KEY, "/");
					soundSharedObject.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
					soundData = soundSharedObject.data;
				} catch (error:Error) {
					soundSharedObject = null;
				}
			}
		}
		
		public function isMuted():Boolean {
			return isMute;
		}
		
		public function unsetMute():void {
			isMute = false;
		}
		
		public function getStoredNonNormalizedVolume():Number {
			if (!soundSharedObject || isNaN(soundData.nonNormalizedVolume)) {
				return cachedNonNormalizedVolume;
			}
			return soundData.nonNormalizedVolume;
		}
		
		public function clearSharedSoundData():void {
			if (!soundSharedObject) {
				return;
			}
			soundSharedObject.clear();
		}
		
		public function getNonNormalizedVolume():Number {
			if (isMute) {
				return 0;
			}
			return getStoredNonNormalizedVolume();
		}
		
		private function onNetStatus(arg1:NetStatusEvent):void {
			if (arg1.info.level == "error") {
				soundSharedObject = null;
			}
		}
		
		public function setMute():void {
			isMute = true;
		}
		
		public function setNonNormalizedVolume(value:Number):void {
			value = isNaN(value) ? 100 : Math.max(value, 0);
			cachedNonNormalizedVolume = value;
			if (!soundSharedObject) {
				return;
			}
			soundData.nonNormalizedVolume = value;
			try {
				soundSharedObject.flush();
			} catch (error:Error) {
			}
		}
	
	}
}
